package cn.zyq.ykb.service.tk.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.zyq.ykb.beans.user.User;
import cn.zyq.ykb.system.common.BaseService;
import cn.zyq.ykb.system.config.consts.redis.RedisH5Keys;
import cn.zyq.ykb.system.config.consts.system.SystemConfig;
import cn.zyq.ykb.system.config.redis.RedisService;
import cn.zyq.ykb.system.enums.core.ResponseCodeEnum;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.utils.Base64Util;
import cn.zyq.ykb.system.utils.MD5Util;
import com.github.pagehelper.PageHelper;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import cn.zyq.ykb.mapper.tk.TUserMapper;
import cn.zyq.ykb.beans.tk.TUser;
import cn.zyq.ykb.service.tk.TUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.zyq.ykb.system.common.PageParam;
import com.github.pagehelper.PageInfo;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户Service业务层处理
 *
 * @author SystemAuth
 * @date 2023-07-03
 */
@Service
public class TUserServiceImpl  extends BaseService implements TUserService {

    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private RedisService redisService;
    /**
     * 查询用户
     *
     * @param tUserID 用户主键
     * @return 用户
     */
    @Override
    public TUser selectTUserByTUserID(Integer tUserID) {
        TUser tUser = tUserMapper.selectByPrimaryKey(tUserID);
        if (tUser.getDeleted() == 1) {
            return null;
        }
        return tUser;
    }

    /**
     * 查询用户
     *
     * @param serviceID 业务ID
     * @return 用户
     */
    @Override
    public TUser selectTUserByServiceID(String serviceID) {
        TUser param = new TUser();
        param.setDeleted(0);
        param.setServiceID(serviceID);
        return this.tUserMapper.selectOne(param);
    }

    /**
     * 查询用户列表
     *
     * @param pageParam
     * @return 用户
     */
    @Override
    public PageInfo<TUser> selectTUserList(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        List<TUser> list = this.tUserMapper.list(pageParam.getKv());
        return new PageInfo<>(list);
    }

    /**
     * 查询用户列表
     *
     * @param pageParam
     * @return 用户
     */
    @Override
    public List<TUser> selectTUserAllList(PageParam pageParam) {
        return this.tUserMapper.list(pageParam.getKv());
    }
    /**
     * 新增用户
     *
     * @param param 用户
     * @return 结果
     */
    @Override
    public int insertTUser(TUser param) {
        this.setCreateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.tUserMapper.insertSelective(param);
    }

    /**
     * 修改用户
     *
     * @param param 用户
     * @return 结果
     */
    @Override
    public int updateTUser(TUser param) {
        this.setUpdateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.tUserMapper.updateByPrimaryKeySelective(param);
    }

    @Override
    public String getCacheKey(String key) {
        return RedisH5Keys.SESSIONID_KEY(key);
    }

    @Override
    public User getFromCache(String key) {
        return this.redisService.getCacheObject(this.getCacheKey(key));
    }

    @Override
    public void setToCache(User user) {
        String cacheKey = this.getCacheKey(user.getToken());
        this.redisService.setCacheObject(cacheKey, user);
        this.redisService.expire(user.getToken(), SystemConfig.timeoutH5, TimeUnit.HOURS);
    }

    @Override
    public void deleteForCache(String key) {
        this.redisService.deleteObject(this.getCacheKey(key));
    }


    @Override
    public TUser register(String phone, String smsCode) {
        if (StrUtil.isEmpty(phone)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"手机号必传");
        }
        if (StrUtil.isEmpty(smsCode)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"短信验证码必传");
        }
//        // 校验短信验证码
//        String smsCodeKey = RedisH5Keys.SMSCODE_KEY(phone);
//        String existedSmsCode  = redisService.getCacheObject(smsCodeKey);
//        //校验验证码
//        if (StringUtils.isEmpty(existedSmsCode)) {
//            throw new RuntimeException("短信验证码不存在或已过期");
//        }
//        if (!existedSmsCode.equals(smsCode)){
//            throw new BusinessException(ResponseCodeEnum.ERROR, "短信验证码输入错误");
//        }
        //根据手机号校验当前用户是注册还是登录
        TUser param = new TUser();
        param.setPhone(phone);
        param.setDeleted(0);
        TUser tUser = this.tUserMapper.selectOne(param);
        //存在就是登录
        if (BeanUtil.isNotEmpty(tUser)){
            tUser.setToken(this.uuid());
            String cacheKey = this.getCacheKey(tUser.getToken());
            this.redisService.setCacheObject(cacheKey, tUser);
            this.redisService.expire(tUser.getToken(), SystemConfig.timeoutH5, TimeUnit.HOURS);
            this.tUserMapper.updateByPrimaryKeySelective(tUser);
//            //最后清理下验证码
//            if(redisService.hasKey(smsCodeKey)){
//                this.deleteForCache(smsCodeKey);
//            }
            return tUser;
        //不存在就是新增用户
        }else {
            TUser user = new TUser();
            user.setPhone(phone);
            user.setNickName(phone);
            user.setToken(this.uuid());
            String cacheKey = this.getCacheKey(user.getToken());
            this.redisService.setCacheObject(cacheKey, user);
            this.redisService.expire(user.getToken(), SystemConfig.timeoutH5, TimeUnit.HOURS);
            this.setCreateBaseData(user,new User());
            this.tUserMapper.insertSelective(user);
            //最后清理下验证码
//            if(redisService.hasKey(smsCodeKey)){
//                this.deleteForCache(smsCodeKey);
//            }
            return user;
        }
    }

    @Override
    public TUser login(String phone, String smsCode) {
        if (StrUtil.isEmpty(phone)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"手机号必传");
        }
        if (StrUtil.isEmpty(smsCode)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"密码必传");
        }
        TUser param = new TUser();
        param.setPhone(phone);
        param.setDeleted(0);
        TUser tUser = this.tUserMapper.selectOne(param);
        if (BeanUtil.isEmpty(tUser)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"该手机号暂未注册，请先注册后登录");
        }
        if (StringUtils.isEmpty(tUser.getPassword())){
            throw new BusinessException(ResponseCodeEnum.ERROR,"该用户未使用密码注册，请使用短信验证码登录");
        }
//        String encode = MD5Util.encode(smsCode);
//        if (!encode.equals(tUser.getPassword())){
//            throw new BusinessException(ResponseCodeEnum.ERROR,"当前登录密码不正确");
//        }
        TUser updateInstance = this.getUpdateInstance(TUser.class);
        updateInstance.setToken(this.uuid());
        updateInstance.setTUserID(tUser.getTUserID());
        String cacheKey = this.getCacheKey(tUser.getToken());
        this.redisService.setCacheObject(cacheKey, updateInstance);
        this.redisService.expire(updateInstance.getToken(), SystemConfig.timeoutH5, TimeUnit.HOURS);
        this.tUserMapper.updateByPrimaryKeySelective(updateInstance);
        return tUser;
    }

    @Override
    public TUser loginByPassword(String phone, String smsCode, String password) {
        if (StrUtil.isEmpty(phone)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"手机号必传");
        }
        if (StrUtil.isEmpty(smsCode)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"短信验证码必传");
        }
        if (StrUtil.isEmpty(password)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"密码必传");
        }
        TUser param = new TUser();
        param.setPhone(phone);
        param.setDeleted(0);
        TUser tUser = this.tUserMapper.selectOne(param);
        if (BeanUtil.isNotEmpty(tUser)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"该手机号已经注册，请直接登录");
        }
        // 校验短信验证码
        String smsCodeKey = RedisH5Keys.SMSCODE_KEY(phone);
        String existedSmsCode  = redisService.getCacheObject(smsCodeKey);
        //校验验证码
        if (StringUtils.isEmpty(existedSmsCode)) {
            throw new RuntimeException("短信验证码不存在或已过期");
        }
        if (!existedSmsCode.equals(smsCode)){
            throw new BusinessException(ResponseCodeEnum.ERROR, "短信验证码输入错误");
        }
        TUser insert = new TUser();
        insert.setPhone(phone);
        insert.setPassword(MD5Util.encode(password));
        insert.setToken(this.uuid());
        insert.setNickName(phone);
        String cacheKey = this.getCacheKey(insert.getToken());
        this.redisService.setCacheObject(cacheKey, insert);
        this.redisService.expire(insert.getToken(), SystemConfig.timeoutH5, TimeUnit.HOURS);
        this.setCreateBaseData(insert,new User());
        this.tUserMapper.insertSelective(insert);
        //最后清理下验证码
        if(redisService.hasKey(smsCodeKey)){
            this.deleteForCache(smsCodeKey);
        }
        return insert;
    }


}
